package com.blb.thread;

import java.util.concurrent.Semaphore;

/**
 * 信号量案例
 */
public class SemaphoneDemo {

    public static void main(String[] args) {
        //创建信号量对象
        Semaphore semaphore = new Semaphore(10);
        //限制只有10个线程能执行
        for (int i = 0; i < 100; i++) {
            final int n = i;
            new Thread(() -> {
                //消耗一个信号量
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "消耗了信号量" + n);
            }).start();
        }
        try {
            Thread.sleep(3000);
            //释放信号量
            semaphore.release(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
